package com.zx.dao;

import com.zx.domain.User;
import com.zx.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class UserDao {

    //  获取所有的用户信息
    public static List<User> getUsers() {

        try {
            QueryRunner qr = new QueryRunner();
            String sql = "select * from user";
            Connection con = DruidUtils.getConnection();
            List<User> users = qr.query(con, sql, new BeanListHandler<User>(User.class));
            con.close();
            return users;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean addUser(User user) throws SQLException {

        List<User> users = getUsers();
        if(users!=null){
            for(User u:users){
                if(u.getName().equals(user.getName())){
                    return false;
                }
            }
            QueryRunner qr = new QueryRunner();
            String sql = "insert into user values(?,?)";
            Connection con = DruidUtils.getConnection();
            Object[] param = {user.getName(),user.getPassword()};
            qr.update(con, sql, param);
            con.close();
            return true;
        }else{
            QueryRunner qr = new QueryRunner();
            String sql = "insert into user values(?,?)";
            Connection con = DruidUtils.getConnection();
            Object[] param = {user.getName(),user.getPassword()};
            qr.update(con, sql, param);
            con.close();
            return true;
        }
    }

}
